<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >

      <el-form-item label="工位名称" prop="workstationName">
        <el-input v-model="formData.workstationName" placeholder="请输入工位名称" />
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-tree-select
          v-model="formData.department"
          :data="deptList"
          :props="defaultProps"
          check-strictly
          node-key="id"
          placeholder="请选择归属部门"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="工艺顺序" prop="processOrder">
        <el-input-number v-model="formData.processOrder" :min="1" />
      </el-form-item>
      <el-form-item label="工位业务" prop="business">
        <el-select
          v-model="formData.business"
          placeholder="请选择工位业务"
          clearable
          class="!w-240px"
        >
          <el-option label="称重" value="称重" />
          <el-option label="测试" value="测试" />
          <el-option label="称重与二次平衡" value="称重与二次平衡" />
        </el-select>
      </el-form-item>
      <el-form-item label="电子秤" prop="electronicScaleId">
        <el-select
          v-model="formData.electronicScaleId"
          placeholder="请选择"
          clearable
          class="!w-240px"
        >
          <el-option v-for="item in electronicScaleList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否控制" prop="isControl">
        <el-select
          v-model="formData.isControl"
          placeholder="请选择"
          clearable
          class="!w-240px"
        >
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item label="用户" prop="userId">
        <el-select
          v-model="formData.userId"
          placeholder="请选择"
          clearable
          class="!w-240px"
        >
          <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
        </el-select>
      </el-form-item>


      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { WorkstationApi, WorkstationVO } from '@/api/hcxly/workstation/Index'
import * as ElectronicScaleApi from '@/api/hcxly/electronicScale/Index'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from "@/api/system/dept";
import * as UserApi from "@/api/system/user"

/** 工位 表单 */
defineOptions({ name: 'WorkstationForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  workstationIndex: undefined,
  workstationName: undefined,
  department: undefined,
  processOrder: undefined,
  business: undefined,
  isControl: undefined,
  remark: undefined,
  electronicScaleId: undefined,
  electronicScaleName: undefined
})
const electronicScaleList = ref([] as ElectronicScaleApi.EleScaleVO[])

const formRules = reactive({
  workstationName: [{ required: true, message: '工位名称不能为空', trigger: 'blur' }],
  department: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  processOrder: [{ required: true, message: '工艺顺序不能为空', trigger: 'blur' }],
  business: [{ required: true, message: '工位业务不能为空', trigger: 'blur' }],
  isControl: [{ required: true, message: '是否控制不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const deptList = ref<Tree[]>([]) // 部门树形结构

const userList = ref<UserApi.UserVO[]>([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await WorkstationApi.getWorkstation(id)
    } finally {
      formLoading.value = false
    }
  }
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  userList.value = await UserApi.getSimpleUserList()

  getElectronicScaleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as WorkstationVO
    data.electronicScaleName = electronicScaleList.value.find(item => item.id === data.electronicScaleId)?.name
    data.username = userList.value.find(item => item.id === data.userId)?.nickname

    if (formType.value === 'create') {
      await WorkstationApi.createWorkstation(data)
      message.success(t('common.createSuccess'))
    } else {
      await WorkstationApi.updateWorkstation(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    workstationIndex: undefined,
    workstationName: undefined,
    department: undefined,
    processOrder: undefined,
    business: undefined,
    isControl: undefined,
    remark: undefined,
    electronicScaleId: undefined,
    electronicScaleName: undefined
  }
  formRef.value?.resetFields()
}

const getElectronicScaleList = async () => {
  try {
    const data = await ElectronicScaleApi.getElectronicScale({
      pageNo: 1,
      pageSize: 100
    })
    electronicScaleList.value = data.list
  } catch (error) {
    console.error('获取电子秤列表失败:', error)
  }
}

</script>
